//
// Created by fuweicong on 2023/4/20.
#include <jni.h>
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "default.h"
#include "peer_connect_client.h"

fm::PeerConnectClient* peerConnectClient;
void invokeJavaCallback(int peer_id, const char* arg);

void fm::CallbackMessage::message(int peer_id, const char *msg) {
    invokeJavaCallback(peer_id, msg);
}

void test(){
    LOGE("测试");
}

static jobject s_callbackObj;

JavaVM *s_jvm;

JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
    s_jvm = vm;
    return JNI_VERSION_1_6;
}

// 在需要回调时调用此函数
void invokeJavaCallback(int peerId, const char* arg) {
    JNIEnv *env;
    int isAttached = 0;

    // 获取当前线程的 JNIEnv 指针
    if (s_jvm->GetEnv((void **)&env, JNI_VERSION_1_6) == JNI_EDETACHED) {
        s_jvm->AttachCurrentThread(&env, NULL);
        isAttached = 1;
    }

    // 调用 Java 类的实例方法
    jclass callbackClass = env->GetObjectClass(s_callbackObj);
    jmethodID callbackMethod = env->GetMethodID(callbackClass, "message", "(ILjava/lang/String;)V");
    //const char *str = "Hello, world!";
    jstring result = env->NewStringUTF(arg);
    env->CallVoidMethod(s_callbackObj, callbackMethod, peerId, result);

    // 释放局部引用
    env->DeleteLocalRef(callbackClass);

    // 解除线程与 JVM 的绑定
    if (isAttached) {
        s_jvm->DetachCurrentThread();
    }
}

extern "C"
JNIEXPORT void JNICALL
Java_com_fm_webrtc_MainActivity_test(JNIEnv *env, jclass clazz) {
    // TODO: implement test()
    test();
   // new fm::PeerConnectClient();
}



extern "C"
JNIEXPORT void JNICALL
Java_com_fm_webrtc_MainActivity_start(JNIEnv *env, jclass clazz, jobject callback_peer_message) {
    // TODO: implement start()
    s_callbackObj = env->NewGlobalRef(callback_peer_message);
    peerConnectClient = new fm::PeerConnectClient(new fm::CallbackMessage);
    peerConnectClient->start();
}

const char* jString2CString(JNIEnv* env, jstring jstr) {
    const char* cstr = env->GetStringUTFChars(jstr, nullptr);
    env->ReleaseStringUTFChars(jstr, cstr);
    return cstr;
}

extern "C"
JNIEXPORT void JNICALL
Java_com_fm_webrtc_MainActivity_sendMessage(JNIEnv *env, jclass clazz, jint peer_id,
                                            jstring message) {
    // TODO: implement sendMessage()
    peerConnectClient->sendMessage(peer_id, jString2CString(env, message));
}